package cn.jark.elasticjob;

import cn.jark.elasticjob.properties.ElasticJobProperties;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

/**
 * @author 雨一直夏灬(须知少年凌云志, 曾许人间第一流)
 * @since 2020-10-28
 */
@Configuration
@EnableConfigurationProperties(value = {ElasticJobProperties.class})
public class ElasticJobAutoConfiguration {

    private final ElasticJobProperties elasticJobProperties;

    public ElasticJobAutoConfiguration(ElasticJobProperties elasticJobProperties) {
        this.elasticJobProperties = elasticJobProperties;
    }

    @Bean("zkConfig")
    public ZookeeperConfiguration zkConfig() {
        String zookeeper = elasticJobProperties.getZkServers();
        String namespace = elasticJobProperties.getNamespace();
        if (StringUtils.isEmpty(zookeeper) || StringUtils.isEmpty(namespace)) {
            throw new RuntimeException("jark.elastic.job.zkServers or jark.elastic.job.namespace is null, please set the value in application.properties. (jark.elastic.job.zkServers)(jark.elastic.job.namespace)");
        }
        return new ZookeeperConfiguration(zookeeper, namespace);
    }

    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter regCenter(@Qualifier("zkConfig") ZookeeperConfiguration config) {
        return new ZookeeperRegistryCenter(config);
    }


    @Order(100)
    @Bean(initMethod = "init")
    public ElasticJobInit elasticJobInit(ZookeeperRegistryCenter registryCenter) {
        return new ElasticJobInit(registryCenter);
    }


}
